<?

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
#	FILE:			includes/text.php
#	FUNCTION:		Functions for handling text
#	AUTHOR:			Cameron Morrow
#	CREATED:		27/07/2005
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# Just letters
$VALID_CHARS_LETTERS = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z");

$VALID_CHARS_LETTERS_UPPER = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");

# Just numbers
$VALID_CHARS_NUMBERS = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");

# Valid chars for use in IDs etc
$VALID_CHARS_ID = array_merge($VALID_CHARS_LETTERS, $VALID_CHARS_NUMBERS, array("_", "-"));

# Valid chars for use in Names etc
$VALID_CHARS_NAME = array_merge($VALID_CHARS_LETTERS, $VALID_CHARS_NUMBERS, array("_", "-", "'", "\\", " ", "(", ")"));

$VALID_CHAR_LIST = array(
	"numbers" => $VALID_CHARS_NUMBERS,
	"numbersspaces" => array_merge($VALID_CHARS_NUMBERS, array(" ", "(", ")")),
	"ids" => $VALID_CHARS_ID,
	"idsspaces" => array_merge($VALID_CHARS_ID, array(" ")),
	"names" => $VALID_CHARS_NAME,
	"namesupper" => array_merge($VALID_CHARS_NAME, $VALID_CHARS_LETTERS_UPPER),
	"email" => array_merge($VALID_CHARS_ID, array("@", ".")),
	"pagenames" => array_merge($VALID_CHARS_NAME, $VALID_CHARS_LETTERS_UPPER, array("?", "!", ":", ",")),
	"any" => array()
);

/**
 * containsValidChars() checks the passed string to ensure it contains only chars from the passed array
 *
 * @param check_string is the string to check
 * @param valid_chars is the array of valid chars
 *
 * @return whether it is valid or not
*/
function containsValidChars($check_string = "", $valid_chars = array()) {

	# Check for validity
	$valid = true;

	# For each character
	for ($i = 0; $i < strlen($check_string); $i++) {

		# Check if it's in the valid chars
		if (findInArray($valid_chars, substr($check_string, $i, 1)) === false) {
			$valid = false;
		}
	}

	# Return
	return $valid;
}


/**
 * generateRandomPassword() generates a random password
 *
 * @param length is the length of the password to create
 *
 * @return the password
*/
function generateRandomPassword($length = 8) {

	global $VALID_CHARS_LETTERS;
	global $VALID_CHARS_LETTERS_UPPER;
	global $VALID_CHARS_NUMBERS;

	$valid_chars = array_merge($VALID_CHARS_LETTERS, $VALID_CHARS_NUMBERS);

	$password = "";

	for ($i = 0; $i < $length; $i++) {

		$password .= $valid_chars[rand(0, count($valid_chars) - 1)];
	}

	return $password;
}


/**
 * removeTags() completely removes any tags
 *
 * @param input is the input
 *
 * @return the untagged string
*/
function removeTags($input = "") {

	# Remove any tags
	$untagged = "";
	$in_tags = false;
	$end_tag_after_next = false;

	# For each char
	for ($i = 0;  $i < strlen($input); $i++) {

		# If opening a tag
		if ($input[$i] == "<") {
			$in_tags = true;
		}

		# If closing a tag
		if ($i > 0 && $in_tags) {
			if ($input[$i] == ">") {
				$end_tag_after_next = true;
			}
		}

		# As long as we are not in a tag, add
		if (!$in_tags) {
			$untagged .= $input[$i];
		}

		# If ending a tag, finish now
		if ($end_tag_after_next) {
			$end_tag_after_next = false;
			$in_tags = false;
			if (strlen($untagged) > 0) {
				if ($untagged[strlen($untagged) - 1] != " ") {
					$untagged .= " ";
				}
			}
		}
	}

	# Return
	return $untagged;
}


/**
 * removeInvalidChars() removes all chars in a string that are not in the passed array of valid chars
 *
 * @param in_string is the string to parse
 * @param valid_chars is the array of valid chars
 *
 * @return the string with bad chars removed
*/
function removeInvalidChars($in_string = "", $valid_chars = array()) {

	# Create output string
	$out_string = "";

	# For each char
	for ($i = 0; $i < strlen($in_string); $i++) {

		# Check if it's in the valid chars
		if (findInArray($valid_chars, $in_string[$i]) !== false) {
			$out_string .= $in_string[$i];
		}
	}

	# Return
	return $out_string;
}


/**
 * better_strrpos is a version of strrpos that will work with searches of >1 char on PHP 4 and lower
 *
 * @param haystack is the haystack
 * @param needle is the needle
 *
 * @return the index
*/
function better_strrpos($haystack = "", $needle = "") {

	if (strpos(strrev($haystack), strrev($needle)) !== false) {

		# Flip both strings around and search, then adjust position based on string lengths
		return strlen($haystack) - strlen($needle) - strpos(strrev($haystack), strrev($needle));

	} else {

		return false;
	}
}


/**
 * createSelector() creates an HTML <select> with appropriate options
 *
 * @param select_name is the id of the selector
 * @param optionA is an array of the options
 * @param optionValueA is an array of option values, or "num" to use number values
 * @param selected_index is the item to select
 *
 * @return the ready-to-display selector
*/
function createSelector($select_name = "", $option_array = array(), $option_value_array = array(), $selected_index = 0, $javascript_function = "") {

	# Start
	$output = "<select id=\"" . $select_name . "\" name=\"" . $select_name . "\"" . ($javascript_function != "" ? "onchange=\"" . $javascript_function . "\"" : "") . ">\n";

	# For each option
	foreach ($option_array as $key => $option_text) {

		$output .= ($option_value_array == "num") ? "<option value=\"" . $key . "\"" : "<option value=\"" . $option_value_array[$key] . "\"";
		
		$output .= ($key == $selected_index) ? " selected=\"selected\"" : "";
		
		$output .= ">" . $option_text . "</option>";
	}

	# End
	$output .= "</select>\n";

	# Return
	return $output;
}


/**
 * createRadioButtonPair() creates a pair of radio buttons, for use in Yes/No, On/Off etc situations
 *
 * @param button_id is the ID of the radio button pair
 * @param no_option is the text to use for the zero option
 * @param yes_option is the text to use for the one option
 * @param selected_index is the default button to use
 *
 * @return the HTML ready to display
*/
function createRadioButtonPair($button_id = "", $no_option = "No", $yes_option = "Yes", $selected_index = 0) {

	# First Button
	$output = "<input type=\"radio\" name=\"" . $button_id . "\" id=\"" . $button_id . "_0\" value=\"0\"" . (($selected_index == 0) ? " checked=\"checked\"" : "") . " /> <label for=\"" . $button_id . "_0\">" . $no_option . "</label><br />";

	# Second Button
	$output .= "<input type=\"radio\" name=\"" . $button_id . "\" id=\"" . $button_id . "_1\" value=\"1\"" . (($selected_index == 1) ? " checked=\"checked\"" : "") . " /> <label for=\"" . $button_id . "_1\">" . $yes_option . "</label>";

	# Return
	return $output;
}


/**
 * createCheckboxList() creates a list of checkboxes
*/
function createCheckboxList($button_id = "", $name_array = array(), $id_array = "num", $checked_array = array()) {

	$output = "";

	foreach ($name_array as $counter => $name) {

		$id = ($id_array == "num" || !@$id_array[$counter]) ? $counter : @$id_array[$counter];
		$checked = (@array_search($id, $checked_array) !== false) ? " checked=\"checked\"" : "";

		$output .= "<input type=\"checkbox\" name=\"" . $button_id . $id . "\" id=\"" . $button_id . $id . "\"" . $checked . " /> <label for=\"" . $button_id . $id . "\">" . $name . "</label>";
		
		if ($counter < count($name_array) - 1) {
			$output .= "<br />";
		}

	}

	return $output;
}

/**
 * generateActionForm() generates the action form used in the admin
 *
 * @return the HTML ready to print
*/
function generateActionForm() {

	# Global
	global $PAGE_ID;

	# Form
	$output = "<form name=\"actionform\" id=\"actionform\" action=\"" . $PAGE_ID . ".php\" method=\"post\">" .
		"<input type=\"hidden\" name=\"mode\" id=\"mode\" value=\"\" />" .
		"<input type=\"hidden\" name=\"id\" id=\"id\" value=\"\" />" .
		"</form>";

	# Return
	return $output;
}


/**
 * generateAddLink() generates a button that can be clicked to go to the add form
*/
function generateAddLink($add_type = "item") {

	# Global
	global $PAGE_ID;

	# Form
	$output = "<form name=\"addform\" id=\"addform\" action=\"" . $PAGE_ID . ".php\" method=\"post\">" .
		"<p><input type=\"button\" onclick=\"doAction('add', '', false);\" value=\"Add a new " . $add_type . "\" /></p>" .
		"</form>";

	# Return
	return $output;
}


/**
 * generateAddLinkForNewsletters() generates a special add button for the 'Add Newsletter' functionality
*/
function generateAddLinkForNewsletters($add_type = "item") {

	# Global
	global $PAGE_ID;

	# Form
	$output = "<form name=\"addform\" id=\"addform\" action=\"" . $PAGE_ID . ".php\" method=\"post\">" .
		"<p><input type=\"button\" onclick=\"getNewNewsletterName();\" value=\"Add a new " . $add_type . "\" /></p>" .
		"</form>";

	# Return
	return $output;
}


/**
 * generateAddEditColumn() generates an Add/Edit links column for the browse tables
*/
function generateAddEditColumn($index_field, $show_edit = true, $show_delete = true) {
	
	# Create output
	$output = "";

	# If an edit link should be shown
	if ($show_edit) {

		$output .= "\"<a href=\\\"javascript:doAction('edit', '[" . $index_field . "]', false);\\\">Edit</a>";
		
	} else {
		$output .= "\"";
	}
	
	if ($show_edit && $show_delete) {
		$output .= " / ";
	}
	
	if ($show_delete) {
		$output .= "<a href=\\\"javascript:doAction('delete', '[" . $index_field . "]', true);\\\">Delete</a>\"";
	} else {
		$output .= "\"";
	}

	return array("Actions", $output);
}


/**
 * generatePageMoveFlash() generates the page move flash file HTML
 *
 * @param flash_url is the path to use for the flash file
 * @param flash_width is the width
 * @param flash_height is the height
 *
 * @return the HTML ready to be written
*/
function generatePageMoveFlash($flash_url = "../assets/flash/page_move_01.swf", $flash_width = 300, $flash_height = 550) {

	# Generate
	$output = "<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0\" width=\"" . $flash_width . "\" height=\"" . $flash_height . "\" id=\"pagemove\">" .
		"<param name=\"allowScriptAccess\" value=\"sameDomain\" />" .
		"<param name=\"scale\" value=\"noscale\" />" .
		"<param name=\"movie\" value=\"" . $flash_url . "\" />" .
		"<param name=\"quality\" value=\"high\" />" .
		"<param name=\"bgcolor\" value=\"#ffffff\" />" .
		"<embed src=\"" . $flash_url . "\" scale=\"noscale\" quality=\"high\" bgcolor=\"#ffffff\" width=\"" . $flash_width . "\" height=\"" . $flash_height . "\" id=\"pagemove\" name=\"pagemove\" allowScriptAccess=\"sameDomain\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" />" .
		"</object>";

	# Return
	return $output;
}


/**
 * generatePageEditFlash() generates the page edit flash file HTML
 *
 * @param flash_url is the path to use for the flash file
 * @param flash_width is the width
 * @param flash_height is the height
 *
 * @return the HTML ready to be written
*/
function generatePageEditFlash($flash_url = "../assets/flash/editor3_02.swf", $flash_width = 800, $flash_height = 600) {

	# Generate
	$output = "<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0\" width=\"" . $flash_width . "\" height=\"" . $flash_height . "\" id=\"pagemove\">" .
		"<param name=\"allowScriptAccess\" value=\"sameDomain\" />" .
		"<param name=\"scale\" value=\"noscale\" />" .
		"<param name=\"movie\" value=\"" . $flash_url . "\" />" .
		"<param name=\"quality\" value=\"high\" />" .
		"<param name=\"bgcolor\" value=\"#ffffff\" />" .
		"<embed src=\"" . $flash_url . "\" scale=\"noscale\" quality=\"high\" bgcolor=\"#ffffff\" width=\"" . $flash_width . "\" height=\"" . $flash_height . "\" id=\"pagemove\" name=\"pagemove\" allowScriptAccess=\"sameDomain\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" />" .
		"</object>";

	
	# Return
	return $output;
}

#Gerenate Page form for admin pages
function genertatePageForm($Group){
	
	global $PROJECT_DB_TABLES;
	
	$output = "";
	
	$output .= "<div id=\"DIV_ADMINPAGES_CONTENT\" align=\"left\">";
	
	$output .= "<div id=\"DIV_ADMINPAGES_LEFT\">";
	
	$output .= "<table cellspacing=\"0\" align=\"left\">";
	
	$sql = "SELECT distinct p_section FROM ".$PROJECT_DB_TABLES['pages']." order by p_id,p_sort";
	
	$current_data = getRecord($sql);
	
	foreach($current_data as $current_key=>$current_value){
		
		$output.="<tr><td valign=\"top\" style=\"border-color: white;border-style: solid;\"><img id=\""."img_".$current_value["p_section"]."\" src=\"../assets/images/tree/folder_closed.png\" onclick=\"ExpandParentPage('".$current_value["p_section"]."','');\"/></td><td style=\"border-color: white;border-style: solid;\">".$current_value["p_section"]."<br/><div id=\""."div_".$current_value["p_section"]."\"></div></td></tr>";
	}//".$current_value["p_id"]."
	
	if ($Group == 'Developers'){
		
		$junkbox_id = 'junkbox';
		
		$output.= "<tr><td valign=\"top\" style=\"border-color: white;border-style: solid;\"><img id=\"img_".$junkbox_id."_junk\" src=\"../assets/images/tree/folder_closed.png\" onclick=\"ExpandParentPage('".$junkbox_id."','');\"/></td><td style=\"border-color: white;border-style: solid;\">".$junkbox_id."<br/><div id=\""."div_".$junkbox_id."_junk\"></div></td></tr>";
		
	}
	$output .= "</table>";
	
	$output .= "</div>";
	
	$output .= "<div id=\"DIV_ADMINPAGES_RIGHT\">";
	
	$output .= "</div>";
	
	$output .= "</div>";
	
	return $output;
}

#Gerenate Page move form 
function genertatePageMoveForm($flash_width = 800, $flash_height = 600){
	
	global $PROJECT_DB_TABLES;
	
	$output = "";
	
	$output .= "<div align=\"left\" style=\"height:500px;width:100%;overflow:scroll;background-color:#FFFFFF;\">";
	
	$output .= "<table cellspacing=\"0\" align=\"left\">";
	
	$sql = "SELECT distinct p_section FROM ".$PROJECT_DB_TABLES['pages']." order by p_id,p_sort";
	
	$current_data = getRecord($sql);
	
	foreach($current_data as $current_key=>$current_value){
		
		$output.="<tr><td valign=\"top\" style=\"border-color: white;border-style: solid;\"><img id=\""."img_".$current_value["p_section"]."\" src=\"../assets/images/tree/folder_closed.png\" onclick=\"ExpandPage('".$current_value["p_section"]."',true,true);\"/></td><td style=\"border-color: white;border-style: solid;\">".$current_value["p_section"]."<br/><div id=\""."div".$current_value["p_section"]."\"></div></td></tr>";
	}//".$current_value["p_id"]."
	
	$output .= "</table>";
	
	$output .= "</div>";
	
	$output .= "<div>";
	
	$output .= "<img id='img_up' style=\"display:none;\" src=\"../assets/images/tree/arrow_up.png\" onclick=\"MoveUpDown(true);\"/><img id='img_down' style=\"display:none;\" src=\"../assets/images/tree/arrow_down.png\" onclick=\"MoveUpDown(false);\"/>";	
				    
	$output .= "SELECTED ITEM:<label id=\"lblSelected\"></label><label id=\"lblSelectedParent\"></label><label id=\"lblSelectedSection\"></label>";
	
	$output .= "</div>";
	
	return $output;
}

/**
 * generatePageSelectFlashInput() generates the flash page selector
 *
 * @return the output
*/
function generatePageSelectFlashInput($current_parent="",$current_section="") {
	# Globals
	global $PASSED_ID;
	
	global $PROJECT_DB_TABLES;

	# Output
	$output = "<tr class=\"norightborder\"><td>Select Parent:</td>";

	# Flash URL
	$flash_url = $flash_filename = "../assets/flash/page_move_01.swf?mode=select&host=../&passed_width=300&passed_height=300&selected_page_id=parentof:" . $PASSED_ID;

	# Add flash page selector
	$output .= "<td align=\"left\">";//. generatePageMoveFlash($flash_url, 300, 300);
	
	# Add Hidden Fields
	$output .= "<input type=\"text\" name=\"p-parent\" id=\"p-parent\" value=\"".$current_parent."\" />";
	$output .= "<input type=\"text\" name=\"p-section\" id=\"p-section\" value=\"".$current_section."\" />";
	
	#Test HTML PAGE
	$output .= "<div align=\"left\" style=\"height:500px;width:100%;overflow:scroll;background-color:#FFFFFF;\">";
	$output .= "<table cellspacing=\"0\" align=\"left\">";
	$sql="SELECT distinct p_section FROM ".$PROJECT_DB_TABLES['pages']." order by p_id,p_sort";
	$current_data=getRecord($sql);
	foreach($current_data as $current_key=>$current_value){
		$output.="<tr><td valign=\"top\" style=\"border-color: white;border-style: solid;\"><img id=\""."img_".$current_value["p_section"]."\" src=\"../assets/images/tree/folder_closed.png\" onclick=\"ExpandPage('".$current_value["p_section"]."',true,false);\"/></td>";
		$output.="<td style=\"border-color: white;border-style: solid;\"><a id=\"a_".$current_value["p_section"]."\" onclick=\"\" href=\"javascript:foo('','".$current_value["p_section"]."');\" style=\"text-decoration:none;\">".$current_value["p_section"]."</a><br/><div id=\""."div".$current_value["p_section"]."\"></div></td></tr>";
	}//".$current_value["p_id"]."
	$output .= "</table>";
	$output .= "</div>";
	
	$output .= "<div>";
	$output .= "SELECTED ITEM:<label id=\"lblSelected\"></label>";
	$output .= "</div>";
	# Close
	$output .= "</td></tr>";

	return $output;

}

/**
 * parseFlashXML() parses the flash XML into HTML
 *
 * @param flash_xml is the flash XML
 *
 * @return the ready to print HTML
*/
function parseFlashXML1($flash_xml = "") {

	# Check it is valid XML
	if (substr($flash_xml, 0, 5) != "<?xml") {

		# Return unformatted
		return $flash_xml;
	}

	# Before we parse the XML, grab any XHTML blocks and store them to be dumped back in later
	$xhtml_blocks = array();
	$flash_xml = explode("<HTMLTextbox display=\"", $flash_xml);
	foreach ($flash_xml as $fc => $xml) {
		if ($fc > 0) {
			$prefix = substr($xml, 0, strpos($xml, ">") + 1);
			$xhtml = substr($xml, 0, strpos($xml, "<"));
			$xhtml = substr($xhtml, strlen($prefix));
			$xhtml_blocks[] = flash_unescape($xhtml);
			$suffix = substr($xml, strlen($prefix) + strlen($xhtml));

			$flash_xml[$fc] = $prefix . "{{XHTML" . (count($xhtml_blocks) - 1) . "}}" . $suffix;
		}
	}
	$flash_xml = implode("<HTMLTextbox display=\"", $flash_xml);


	#$save = createFile("../includes/", "parse-log-" . getFullDate() . "-" . rand(100, 999) . ".txt", $flash_xml);

	$flash_xml = flash_unescape($flash_xml);
	$flash_xml = str_replace(
		array("<HTMLTextbox display=\"block\">", "<HTMLTextbox display=\"inline\">", "</HTMLTextbox>"),
		array("<HTMLTextbox display=\"block\"><![CDATA[", "<HTMLTextbox display=\"inline\"><![CDATA[", "]]></HTMLTextbox>"),
		$flash_xml);

	# Run through XSL parser
	$arguments_flash = array(
		"/_xml" => $flash_xml,
		"/_xsl" => file_get_contents("../../includes/flash/html.xsl")
	);

	# Create XSLT Processor
	$xsltproc_flash = xslt_create();

	# Convert
	$flash_content = xslt_process(
		$xsltproc_flash,
		'arg:/_xml',
		'arg:/_xsl',
		null,
		$arguments_flash
	);

	# Finish
	xslt_free($xsltproc_flash);

	#$save = createFile("../includes/", "parse1-log-" . getFullDate() . "-" . rand(100, 999) . ".txt", $flash_content);

	# Splice XHTML back in
	$flash_content = preg_replace(
		"/\{\{XHTML([0-9]*)\}\}/ie",
		"$" . "xhtml_blocks[\\1]",
		$flash_content);

	# Remove <htmltextbox> tags
	$flash_content = preg_replace(
		array("/<\/*htmltextbox[^>]*>/i", "/>\ *</i"),
		array("", "><"),
		$flash_content);

	# Fix up any dodgy chars
	$flash_content = str_replace(
		array(
			"\r",
			"\t",
			"\n",
			"<br>",
			"    ",
			"<p></p>"
		),
		array(
			"",
			"",
			"",
			"<br />",
			"",
			"<p>&nbsp;</p>"
		),
		$flash_content);
	

	# Parse columns
	$column_id = 1;
	$column_code = "class=\"column\">";
	while (strpos($flash_content, $column_code) !== false && $column_id < 3) {
		$index = strpos($flash_content, $column_code);
		$flash_content = substr($flash_content, 0, $index) . "class=\"column\" id=\"column" . $column_id . "\">" . substr($flash_content, $index + strlen($column_code));
		$column_id++;
	}

	# Return
	return $flash_content;

}


/**
 * parseFlashXML() parses the flash XML into HTML
 *
 * @param flash_xml is the flash XML
 *
 * @return the ready to print HTML
*/
function parseFlashXML($flash_xml = "") {

	# Check it is valid XML
	if (substr($flash_xml, 0, 5) != "<?xml") {

		# Return unformatted
		return $flash_xml;
	}

	# Before we parse the XML, grab any XHTML blocks and store them to be dumped back in later
	$xhtml_blocks = array();
	$flash_xml = explode("<HTMLTextbox display=\"", $flash_xml);
	foreach ($flash_xml as $fc => $xml) {
		if ($fc > 0) {
			$prefix = substr($xml, 0, strpos($xml, ">") + 1);
			$xhtml = substr($xml, 0, strpos($xml, "<"));
			$xhtml = substr($xhtml, strlen($prefix));
			$xhtml_blocks[] = flash_unescape($xhtml);
			$suffix = substr($xml, strlen($prefix) + strlen($xhtml));

			$flash_xml[$fc] = $prefix . "{{XHTML" . (count($xhtml_blocks) - 1) . "}}" . $suffix;
		}
	}
	$flash_xml = implode("<HTMLTextbox display=\"", $flash_xml);


	#$save = createFile("../includes/", "parse-log-" . getFullDate() . "-" . rand(100, 999) . ".txt", $flash_xml);

	$flash_xml = flash_unescape($flash_xml);
	$flash_xml = str_replace(
		array("<HTMLTextbox display=\"block\">", "<HTMLTextbox display=\"inline\">", "</HTMLTextbox>"),
		array("<HTMLTextbox display=\"block\"><![CDATA[", "<HTMLTextbox display=\"inline\"><![CDATA[", "]]></HTMLTextbox>"),
		$flash_xml);

	# Run through XSL parser
	$arguments_flash = array(
		"/_xml" => $flash_xml,
		"/_xsl" => file_get_contents("../includes/flash/html.xsl")
	);

	# Create XSLT Processor
	$xsltproc_flash = xslt_create();

	# Convert
	$flash_content = xslt_process(
		$xsltproc_flash,
		'arg:/_xml',
		'arg:/_xsl',
		null,
		$arguments_flash
	);

	# Finish
	xslt_free($xsltproc_flash);

	#$save = createFile("../includes/", "parse1-log-" . getFullDate() . "-" . rand(100, 999) . ".txt", $flash_content);

	# Splice XHTML back in
	$flash_content = preg_replace(
		"/\{\{XHTML([0-9]*)\}\}/ie",
		"$" . "xhtml_blocks[\\1]",
		$flash_content);

	# Remove <htmltextbox> tags
	$flash_content = preg_replace(
		array("/<\/*htmltextbox[^>]*>/i", "/>\ *</i"),
		array("", "><"),
		$flash_content);

	# Fix up any dodgy chars
	$flash_content = str_replace(
		array(
			"\r",
			"\t",
			"\n",
			"<br>",
			"    ",
			"<p></p>"
		),
		array(
			"",
			"",
			"",
			"<br />",
			"",
			"<p>&nbsp;</p>"
		),
		$flash_content);
	

	# Parse columns
	$column_id = 1;
	$column_code = "class=\"column\">";
	while (strpos($flash_content, $column_code) !== false && $column_id < 3) {
		$index = strpos($flash_content, $column_code);
		$flash_content = substr($flash_content, 0, $index) . "class=\"column\" id=\"column" . $column_id . "\">" . substr($flash_content, $index + strlen($column_code));
		$column_id++;
	}

	# Return
	return $flash_content;

}


/**
 * parseFlashLinks() parses flash links into HTML links
 *
 * @param html is the HTML to parse
 *
 * @return the parsed html
*/
function parseFlashLinks($html = "") {

	return preg_replace(
		array("/<a href\=\"asfunction\:editLink\,([^\,]*)\,[^\"]*\"/i"),
		array("<a href=\"\\1\""),
		$html);
}


/**
 * deTag() replaces < > and their HTML entities
 *
 * @param input is the input
 *
 * @return the replaced output
*/
function deTag($input) {

	return preg_replace(
		array("/</i", "/>/i"),
		array("&lt;", "&gt;"),
		$input);
}


/**
 * formatBytes() formats an amount in bytes
 *
 * @param bytes is the value in bytes
 *
 * @return the formatted output
*/
function formatBytes($bytes) {

	# Convert to integer
	$bytes = (integer) $bytes;

	if ($bytes >= 1099511627776) {
		$return = round($bytes / 1024 / 1024 / 1024 / 1024, 2);
		$suffix = "TB";
	} else if ($bytes >= 1073741824) {
		$return = round($bytes / 1024 / 1024 / 1024, 2);
		$suffix = "GB";
	} else if ($bytes >= 1048576) {
		$return = round($bytes / 1024 / 1024, 2);
		$suffix = "MB";
	} elseif ($bytes >= 1024) {
		$return = round($bytes / 1024, 2);
		$suffix = "KB";
	} else {
		$return = $bytes;
		$suffix = "Byte";
	}

	# Check if single or plural
	if ($return == 1 || $suffix != "Byte") {
		$return .= " " . $suffix;
	} else {
		$return .= " " . $suffix . "s";
	}

	# Return
	return $return;
}


/**
 * adminPagePrintout() is a custom handler for printing the admin page browser
 *
 * @param current_pages is an array of pages
 * @param parent_id is the ID of the parent to show the pages in
 * @param section is the section to be of
*/
function adminPagePrintout($current_pages = array(), $parent_id = "", $section = "site", $depth = 0) {

	global $ROW_COUNT;
	if (!$ROW_COUNT) {
		$ROW_COUNT = 0;
	}

	foreach ($current_pages as $current_page_id => $current_page) {

		if ($current_page["p_parent"] == $parent_id && $current_page["p_section"] == $section && $current_page["p_status"]<3) {
				$padding = "";
				for ($i = 0; $i < $depth; $i++) {
					$padding .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
				}
	
				addContent("<tr" . ($ROW_COUNT % 2 == 0 ? " class=\"alternate\"" : "") . ">" .
					"<td>" . $padding . "<a href=\"../" . $current_page["p_section"] . "/" . $current_page_id . ".php\">" . $current_page["p_name"] . "</a> (" . $current_page_id . ")</td>" .
					"<td>" . getPageStatusName($current_page["p_status"]) . "</td>" .
					"<td><a href=\"javascript:launchPageMove('" . $current_page_id . "');\">Move</a></td>" .
					"<td><a href=\"javascript:launchPagePreview('" . $current_page_id . "');\">Preview</a></td>" .
					"<td><a href=\"javascript:editPageContent('" . $current_page_id . "');\">Content</a></td>" .
					"<td><a href=\"javascript:doAction('edit', '" . $current_page_id . "', false);\">Edit</a> / <a href=\"javascript:doAction('remove', '" . $current_page_id . "', true);\">Remove</a></td></tr>");
	
				$ROW_COUNT++;
	
				#addContent("<p>" . $depth . ": Page: " . $current_page_id . " (Parent: " . $current_page["p_parent"] . ")</p>");
	
				adminPagePrintout($current_pages, $current_page_id, $section, $depth + 1);
		}
	}
}

/**
 * adminPageJunkPrintOut() is a custom handler for printing the admin page browser
 *
 * @param current_pages is an array of pages
 * @param parent_id is the ID of the parent to show the pages in
 * @param section is the section to be of
*/
function adminPageJunkPrintOut($current_pages = array()){
		foreach ($current_pages as $current_page_id => $current_page) {

		if ($current_page["p_status"]==3) {
	
				addContent("<tr>" .
					"<td>".$current_page_id."</td>" .
					"<td>" . getPageStatusName($current_page["p_status"]) . "</td>" .
					"<td><a href=\"javascript:doAction('restore', '" . $current_page_id . "', false);\">Restore</a></td></tr>");		
				#addContent("<p>" . $depth . ": Page: " . $current_page_id . " (Parent: " . $current_page["p_parent"] . ")</p>");
		}
	}
}

/**
 * adminUserPrintOut() is a custom handler for printing the admin page browser
 *
 * @param current_pages is an array of pages
 * @param parent_id is the ID of the parent to show the pages in
 * @param section is the section to be of
*/
function adminUserPrintOut($current_users = array(), $current_groups=array(), $section=""){

	foreach ($current_users as $current_user_id => $current_user) {
			if($section!="Others")
			{
				if($current_user["g_name"]==$section){

					addContent("<tr>" .
					"<td>" . getGroupName1($current_user["u_group"],$current_groups). "</td>".
					"<td>" . $current_user["u_id"] . "</td>".
					"<td>" . $current_user["u_login_name"] . "</td>".
					"<td>" . formatDate($current_user["u_created"]) . "</td>".
					"<td>" . formatDate($current_user["u_lastlogin"]) . "</td>".
					"<td><a href=\"javascript:openChangePasswordAdminWin('" . $current_user_id . "');\">Change Password</a></td>" .
					"<td><a href=\"javascript:doAction('edit', '" . $current_user_id . "', false);\">Edit</a> / <a 		href=\"javascript:doAction('delete', '" . $current_user_id . "', true);\">Delete</a></td></tr>");
				}
			}
			else{
				if($current_user["g_name"]!="Developers" && $current_user["g_name"]!="Administrators"){
					addContent("<tr>" .
					"<td>" . getGroupName1($current_user["u_group"],$current_groups). "</td>".
					"<td>" . $current_user["u_id"] . "</td>".
					"<td>" . $current_user["u_login_name"] . "</td>".
					"<td>" . formatDate($current_user["u_created"]) . "</td>".
					"<td>" . formatDate($current_user["u_lastlogin"]) . "</td>".
					"<td><a href=\"javascript:openChangePasswordAdminWin('" . $current_user_id . "');\">Change Password</a></td>" .
					"<td><a href=\"javascript:doAction('edit', '" . $current_user_id . "', false);\">Edit</a> / <a 		href=\"javascript:doAction('delete', '" . $current_user_id . "', true);\">Delete</a></td></tr>");
				}
			}
	}
}

# Implement equivalents of Flash's 'escape' and 'unescape' functions
function flash_escape($input) {
	return rawurlencode($input);
}

function flash_unescape($input) {
	return rawurldecode($input);
}

function back($input) {
	return $input;
}

#Add hyperlink for the key words
function glossary_replace($main_output="",$seaching_content=array()){
						  
	foreach($seaching_content as $seaching_key=>$searching_value){
							  
		$key_word_count=substr_count(strtolower($main_output),strtolower($searching_value['gl_term']));
		//echo $key_word_count."---".$searching_value['gl_term']."<br/>";
							
		if($key_word_count!=0)//&& $searching_value['gl_letter']!='Symbol'
		{
			$Popup_value = $searching_value['gl_descripto'];
			
			#Set the value for the item need to search		
			$search_item = $searching_value['gl_term'];
			
			#Set the value for lower case searching item
			$search_item_lowercase = strtolower($searching_value['gl_term']);

			#Set the value for the upper case searching item
			$search_item_uppercase = strtoupper($search_item_lowercase);

			#Set the value for the word with their first letter as uppercase
			$search_item_ucfirst = ucfirst($search_item_lowercase);
			
			$search_item1 = str_replace("'","\'",$search_item);
			
			$search_item_lowercase1 = str_replace("'","\'",$search_item_lowercase);
			
			$search_item_uppercase1 = str_replace("'","\'",$search_item_uppercase);
			
			$search_item_ucfirst1 = str_replace("'","\'",$search_item_ucfirst);
			
			$term_link = "<a id=\"".$search_item."\" style=\"text-decoration:none;color:#808080;\" onmouseover=\"omoChangeFont('".$search_item1."')\" onmouseout=\"omoChangeFontBack('".$search_item1."')\" href=\"javascript:ShowGlossaryPopup('popup','".Encoding($searching_value['gl_descripto'])."');\">".$search_item."</a>";
			
			$term_link_lowercase = "<a id=\"".$search_item_lowercase."\" onmouseover=\"omoChangeFont('".$search_item_lowercase1."')\" onmouseout=\"omoChangeFontBack('".$search_item_lowercase1."')\"   style=\"text-decoration:none;color:#808080;\" href=\"javascript:ShowGlossaryPopup('popup','".Encoding($searching_value['gl_descripto'])."');\">".$search_item_lowercase."</a>";
			
			$term_link_uppercase = "<a id=\"".$search_item_uppercase."\" onmouseover=\"omoChangeFont('".$search_item_uppercase1."')\" onmouseout=\"omoChangeFontBack('".$search_item_uppercase1."')\"  style=\"text-decoration:none;color:#808080;\" href=\"javascript:ShowGlossaryPopup('popup','".Encoding($searching_value['gl_descripto'])."');\">".$search_item_uppercase."</a>";
			
			$term_link_ucfirst = "<a id=\"".$search_item_ucfirst."\" onmouseover=\"omoChangeFont('".$search_item_ucfirst1."')\" onmouseout=\"omoChangeFontBack('".$search_item_ucfirst1."')\" style=\"text-decoration:none;color:#808080;\" href=\"javascript:ShowGlossaryPopup('popup','".Encoding($searching_value['gl_descripto'])."');\">".$search_item_ucfirst."</a>";
			
			$count_keyword=0;
								
			preg_match_all("#\<[pP](.+?)\<\/[pP]\>#", $main_output, $matches_p_a);
							   	
			if(count($matches_p_a)>=1){
									
				$index_0=0;
								
				$searching_item_final="";
			
				$replacing_item_final="";
									
				foreach($matches_p_a[0] as $matches_key_sub_p_a=>$matches_value_sub_p_a){	
								  									  
					if($searching_value['gl_letter']!='Symbol'){
								  		
						#lowercase with blank space start and end
						$index_1_low=strpos($matches_value_sub_p_a," ".$search_item_lowercase." ",0);
						if($index_1_low!=false){
							$index_0=$index_1_low;
							$searching_item_final=" ".$search_item_lowercase." ";
							$replacing_item_final=" ".$term_link_lowercase." ";
						}
						
						#uppercase with blank space start and end
						$index_1_upper=strpos($matches_value_sub_p_a," ".$search_item_uppercase." ",0);
						if($index_1_upper!=false){
							if($index_0!=0 || $index_1_upper<$index_0){
								$index_0=$index_1_upper;
								$searching_item_final=" ".$search_item_uppercase." ";
								$replacing_item_final=" ".$term_link_uppercase." ";
							}	
						}
						
						#The term with uppercase as first letter which start from blank space and end with blank space
						$index_1_uc=strpos($matches_value_sub_p_a," ".$search_item_ucfirst." ",0);
						if($index_1_uc!=false){
							if($index_0==0||$index_1_uc<$index_0){
								  $index_0=$index_1_uc;
								  $searching_item_final=" ".$search_item_ucfirst." ";
								  $replacing_item_final=" ".$term_link_ucfirst." ";
							  }
						}
						
						#Lowercase item start with blank space end by Comma
						$index_2_low=strpos($matches_value_sub_p_a," ".$search_item_lowercase.",",0);
						if($index_2_low!=false){
							if($index_2_low<$index_0 || $index_0==0){
								$index_0=$index_2_low;
								$searching_item_final=" ".$search_item_lowercase.",";
								$replacing_item_final=" ".$term_link_lowercase.",";
							}
						}
						
						#Uppercase item start with blank space end by Comma
						$index_2_upper=strpos($matches_value_sub_p_a," ".$search_item_uppercase.",",0);
						if($index_2_upper!=false){
							if($index_2_upper<$index_0 || $index_0==0){
								$index_0=$index_2_upper;
								$searching_item_final=" ".$search_item_uppercase.",";
								$replacing_item_final=" ".$term_link_uppercase.",";
							}
						}
						
						#First upper case item start with blank space end by Comma
						$index_2_uc=strpos($matches_value_sub_p_a," ".$search_item_ucfirst.",",0);
						if($index_2_uc!=false){
							if($index_2_uc<$index_0 || $index_0==0){
								$index_0=$index_2_uc;
								$searching_item_final=" ".$search_item_ucfirst.",";
								$replacing_item_final=" ".$term_link_ucfirst.",";
							}
						}
						
						#Lowercase item start with blank space end by Period
						$index_3_low=strpos($matches_value_sub_p_a," ".$search_item_lowercase.".",0);
						if($index_3_low!=false){
							if($index_3_low<$index_0 || $index_0==0){
								$index_0=$index_3_low;
								$searching_item_final=" ".$search_item_lowercase.".";
								$replacing_item_final=" ".$term_link_lowercase.".";
							}
						}
						
						#Uppercase item start with blank space end by Period
						$index_3_upper=strpos($matches_value_sub_p_a," ".$search_item_uppercase.".",0);
						if($index_3_upper!=false){
							if($index_3_upper<$index_0 || $index_0==0){
								$index_0=$index_3_upper;
								$searching_item_final=" ".$search_item_uppercase.".";
								$replacing_item_final=" ".$term_link_uppercase.".";
							}
						}
						
						#First upper case item start with blank space end by Period
						$index_3_uc=strpos($matches_value_sub_p_a," ".$search_item_ucfirst.".",0);
						if($index_3_uc!=false){
							if($index_3_uc<$index_0 || $index_0==0){
								$index_0=$index_3_uc;
								$searching_item_final=" ".$search_item_ucfirst.".";
								$replacing_item_final=" ".$term_link_ucfirst.".";
							}
						}
						
						#Lowercase item start with > end by </
						$index_4_low=strpos($matches_value_sub_p_a,">".$search_item_lowercase."</",0);
						if($index_4_low!=false){
							if($index_4_low<$index_0 || $index_0==0){
								$index_0=$index_4_low;
								$searching_item_final=">".$search_item_lowercase."</";
								$replacing_item_final=">".$term_link_lowercase."</";
							}
						}
						
						#Upper item start with > end by </
						$index_4_upper=strpos($matches_value_sub_p_a,">".$search_item_uppercase."</",0);
						if($index_4_upper!=false){
							if($index_4_upper<$index_0 || $index_0==0){
								$index_0=$index_4_upper;
								$searching_item_final=">".$search_item_uppercase."</";
								$replacing_item_final=">".$term_link_uppercase."</";
							}
						}
						
						#First item start with > end by </
						$index_4_uc=strpos($matches_value_sub_p_a,">".$search_item_ucfirst."</",0);
						if($index_4_uc!=false){
							if($index_4_uc<$index_0 || $index_0==0){
								$index_0=$index_4_uc;
								$searching_item_final=">".$search_item_ucfirst."</";
								$replacing_item_final=">".$term_link_ucfirst."</";
							}
						}
						
						#Lowercase item start with blankspace end by </
						$index_5_low=strpos($matches_value_sub_p_a," ".$search_item_lowercase."</",0);
						if($index_5_low!=false || $index_0==0){
							if($index_5_low<$index_0){
								$index_0=$index_5_low;
								$searching_item_final=" ".$search_item_lowercase."</";
								$replacing_item_final=" ".$term_link_lowercase."</";
							}
						}
						
						#Upper item start with blankspace end by </
						$index_5_upper=strpos($matches_value_sub_p_a," ".$search_item_uppercase."</",0);
						if($index_5_upper!=false || $index_0==0){
							if($index_5_upper<$index_0){
								$index_0=$index_5_upper;
								$searching_item_final=" ".$search_item_uppercase."</";
								$replacing_item_final=" ".$term_link_uppercase."</";
							}
						}
						
						#First item start with blankspace end by </
						$index_5_uc=strpos($matches_value_sub_p_a," ".$search_item_ucfirst."</",0);
						if($index_5_uc!=false){
							if($index_5_uc<$index_0 || $index_0==0){
								$index_0=$index_5_uc;
								$searching_item_final=" ".$search_item_ucfirst."</";
								$replacing_item_final=" ".$term_link_ucfirst."</";
							}
						}
						
						#Lowercase item start with > end by blank space
						$index_6_low=strpos($matches_value_sub_p_a,">".$search_item_lowercase." ",0);
						if($index_6_low!=false){
							if($index_6_low<$index_0 || $index_0==0){
								$index_0=$index_6_low;
								$searching_item_final=">".$search_item_lowercase." ";
								$replacing_item_final=">".$term_link_lowercase." ";
							}
						}
						
						#Upper item start with > end by blank space
						$index_6_upper=strpos($matches_value_sub_p_a,">".$search_item_uppercase." ",0);
						if($index_6_upper!=false){
							if($index_6_upper<$index_0 || $index_0==0){
								$index_0=$index_6_upper;
								$searching_item_final=">".$search_item_uppercase." ";
								$replacing_item_final=">".$term_link_uppercase." ";
							}
						}
						
						#First item start with blankspace end by </
						$index_6_uc=strpos($matches_value_sub_p_a,">".$search_item_ucfirst." ",0);
						if($index_6_uc!=false){
							if($index_6_uc<$index_0 || $index_0==0){
								$index_0=$index_6_uc;
								$searching_item_final=">".$search_item_ucfirst." ";
								$replacing_item_final=">".$term_link_ucfirst." ";
							}
						}
						
						#Lowercase item start with blank space end by quotation marks
						$index_7_low=strpos($matches_value_sub_p_a," ".$search_item_lowercase.";",0);
						if($index_7_low!=false){
							if($index_7_low<$index_0 || $index_0==0){
								$index_0=$index_7_low;
								$searching_item_final=" ".$search_item_lowercase.";";
								$replacing_item_final=" ".$term_link_lowercase.";";
							}
						}
						
						#Upper item start with blank space end by quotation marks
						$index_7_upper=strpos($matches_value_sub_p_a," ".$search_item_uppercase.";",0);
						if($index_7_upper!=false){
							if($index_7_upper<$index_0 || $index_0==0){
								$index_0=$index_7_upper;
								$searching_item_final=" ".$search_item_uppercase.";";
								$replacing_item_final=" ".$term_link_uppercase.";";
							}
						}
						
						#First item start with blank space end by quotation marks
						$index_7_uc=strpos($matches_value_sub_p_a," ".$search_item_ucfirst.";",0);
						if($index_7_uc!=false){
							if($index_7_uc<$index_0 || $index_0==0){
								$index_0=$index_7_uc;
								$searching_item_final=" ".$search_item_ucfirst.";";
								$replacing_item_final=" ".$term_link_ucfirst.";";
							}
						}
						
						#Lowercase item start with blank space end by s
						$index_8_low=strpos($matches_value_sub_p_a," ".$search_item_lowercase."s",0);
						if($index_8_low!=false){
							if($index_8_low<$index_0 || $index_0==0){
								$index_0=$index_8_low;
								$searching_item_final=" ".$search_item_lowercase.";";
								$replacing_item_final=" ".$term_link_lowercase.";";
							}
						}
						
						#Upper item start with blank space end by quotation marks
						$index_8_upper=strpos($matches_value_sub_p_a," ".$search_item_uppercase."s",0);
						if($index_8_upper!=false){
							if($index_8_upper<$index_0 || $index_0==0){
								$index_0=$index_8_upper;
								$searching_item_final=" ".$search_item_uppercase.";";
								$replacing_item_final=" ".$term_link_uppercase.";";
							}
						}
						
						#First item start with blank space end by quotation marks
						$index_8_uc=strpos($matches_value_sub_p_a," ".$search_item_ucfirst."s",0);
						if($index_8_uc!=false){
							if($index_8_uc<$index_0 || $index_0==0){
								$index_0=$index_8_uc;
								$searching_item_final=" ".$search_item_ucfirst.";";
								$replacing_item_final=" ".$term_link_ucfirst.";";
							}
						}
					}
					else{
									
						$index_1=strpos($matches_value_sub_p_a," ".$search_item." ",0);
										
						if($index_1!=false){
							if($index_1<$index_0 || $index_0==0){
								$index_0=$index_1;
								$searching_item_final=" ".$search_item." ";
								$replacing_item_final=" ".$term_link." ";
							}
						}
										
						$index_2=strpos($matches_value_sub_p_a," ".$search_item.",",0);
						if($index_2!=false){
							if($index_2<$index_0 || $index_0==0){
								$index_0=$index_2;
								$searching_item_final=" ".$search_item.",";
								$replacing_item_final=" ".$term_link.",";
							}
						}
										
						$index_3=strpos($matches_value_sub_p_a," ".$search_item.".",0);
						if($index_3!=false){
							if($index_3<$index_0 || $index_0==0){
								$index_0=$index_3;
								$searching_item_final=" ".$search_item.".";
								$replacing_item_final=" ".$term_link.".";
							}
						}
						
						$index_4=strpos($matches_value_sub_p_a,">".$search_item."</",0);
						if($index_4!=false){
							if($index_4<$index_0 || $index_0==0){
								$index_0=$index_4;
								$searching_item_final=">".$search_item."</";
								$replacing_item_final=">".$term_link."</";
							}
						}
	
						$index_5=strpos($matches_value_sub_p_a," ".$search_item."</",0);
						if($index_5!=false){
							if($index_5<$index_0 || $index_0==0){
								$index_0=$index_5;
								$searching_item_final=" ".$search_item."</";
								$replacing_item_final=" ".$term_link."</";
							}
						}
				
						$index_6=strpos($matches_value_sub_p_a,">".$search_item." ",0);
						if($index_6!=false){
							if($index_6<$index_0 || $index_0==0){
								$index_0=$index_6;
								$searching_item_final=">".$search_item." ";
								$replacing_item_final=">".$term_link." ";
							}
						}			
					
						$index_7=strpos($matches_value_sub_p_a," ".$search_item.";",0);
						if($index_7!=false){
							if($index_7<$index_0 || $index_0==0){
								$index_0=$index_7;
								$searching_item_final=" ".$search_item.";";
								$replacing_item_final=" ".$term_link.";";
							}
						}
					}
									  
					//echo $count_keyword."=>".$searching_value["gl_term"].$count_keyword."<br/>";
					if($count_keyword<1 && $searching_item_final!=""){
					  //echo $count_keyword."=>".$searching_value["gl_term"].$count_keyword."<br/>";
					  //echo "rgsegrser:".$searching_item_final."<br/>";
					$replacement_Item=preg_replace('('.$searching_item_final.')',$replacing_item_final,$matches_value_sub_p_a,1,$count);
					$count_keyword+=$count;
					
					$main_output=str_replace($matches_value_sub_p_a,$replacement_Item,$main_output);
				  }
			  }
		  }
	  }
   }	
   return $main_output;
}

function removetable($content="")
{
	$table_removed=preg_replace("#\<table(.+?)\>#", "", $content);

	$table_removed=str_replace("</table>", "", $table_removed);

	$table_removed=preg_replace("#\<tr(.+?)\>#", "", $table_removed);

	$table_removed=preg_replace("#\<td(.+?)\>#", "", $table_removed);

	$table_removed=str_replace("</tr>", "", $table_removed);
	
	$table_removed=str_replace("</td>", "", $table_removed);
	
	return $table_removed;
}

function ReplaceMulitpleChoice($main_output="",$flag_pdf=false,$flag_xml=false){
	
	$flag_multi=false;
	
	if(substr_count($main_output,"<multiple-choice>")>=2&&substr_count($main_output,"</multiple-choice>")>=2){
		$flag_multi=true;
	}
	
	$content_multiple_choice="";
							  
	preg_match_all("#\<multiple-choice\>(.+?)\<\/multiple-choice\>#", $main_output, $matches_p_a);
	
	$mc_times=0;
	
	foreach($matches_p_a as $matches_p_a_key=>$matches_p_a_value){
		
		$tr_pieces=explode("^",$matches_p_a_value[$mc_times]);
								  
		$tr_array=array();
		
		$content_multiple_choice.="<TABLE border=\"0\" id=\"muli_table\">";
		
		foreach($tr_pieces as $tr_key=>$tr_value){

			$content_multiple_choice.="<TR>";
			
			$td_array=explode("@",$tr_value);
	
			if($flag_pdf==false){
	
				$content_multiple_choice.="<TD id=\"".$mc_times."_".$tr_key."_0"."\">";
				
				if($td_array[1]=="true"){
				
					$content_multiple_choice.="<img id=\"img_".$mc_times."_".$tr_key."_0\" src=\"../site_specific/assets/images/grey_button.png\" onclick=\"muliple_choice_click('".$mc_times."','".$tr_key."','true')\"/>";		
				}
				else{
					
					$content_multiple_choice.="<img id=\"img_".$mc_times."_".$tr_key."_0\" src=\"../site_specific/assets/images/grey_button.png\" onclick=\"muliple_choice_click('".$mc_times."','".$tr_key."','false')\"/>";			
				}
				
				$content_multiple_choice.="</TD>";
			}
			else{
			}
			
			foreach($td_array as $td_key=>$td_value){	
		
				if($td_key=="0"){
					$content_multiple_choice.="<TD id=\"td_".$mc_times."_".$tr_key."_1"."\" valign=\"top\">";
					$content_multiple_choice.=$td_value;
					$content_multiple_choice.="</TD>";
				}
				else if($td_key=="1"){
					if($flag_pdf==true){
						$content_multiple_choice.="<TD id=\"td_".$mc_times."_".$tr_key."_2"."\" valign=\"top\">";
						
						$content_multiple_choice.=$td_value;
						
						$content_multiple_choice.="</TD>";
					}
					else{
						if($flag_xml==true){
							$content_multiple_choice.="<TD id=\"td_".$mc_times."_".$tr_key."_2"."\" valign=\"top\"><p class=\"displaynone\">";
							$content_multiple_choice.=$td_value;
							$content_multiple_choice.="</p></TD>";
						}
						else{
							$content_multiple_choice.="<TD id=\"td_".$mc_times."_".$tr_key."_2"."\" valign=\"top\"  style=\"display:none;\">";
							$content_multiple_choice.=$td_value;
							$content_multiple_choice.="</TD>";
						}
					}
					
				}
				else if($td_key=="2"){
					if($flag_pdf==true){
						$content_multiple_choice.="<TD id=\"td_".$mc_times."_".$tr_key."_3"."\" width=\"75%\" valign=\"top\">";
						$content_multiple_choice.=$td_value;
							
						$content_multiple_choice.="</TD>";
					}
					else{
						if($flag_xml==true){
							$content_multiple_choice.="<TD id=\"td_".$mc_times."_".$tr_key."_3"."\" valign=\"top\"><p class=\"displaynone\">";
							$content_multiple_choice.=$td_value;
							$content_multiple_choice.="</p></TD>";
						}
						else{
							$content_multiple_choice.="<TD id=\"td_".$mc_times."_".$tr_key."_3"."\" valign=\"top\"  style=\"display:none;\">";
							$content_multiple_choice.=$td_value;
							$content_multiple_choice.="</TD>";
						}
					}
					
				}								  
			}
			
			$content_multiple_choice.="</TR>";						  
		}
		
		$content_multiple_choice.="</TABLE>";
		
		$main_output=str_replace($matches_p_a_value[$mc_times],$content_multiple_choice,$main_output);
		
		$content_multiple_choice="";
		
		if($flag_multi==true){
			$mc_times+=1;
		}
	}
	
	$main_output=str_replace("<multiple-choice>","",$main_output);
	
	$main_output=str_replace("</multiple-choice>","",$main_output);
	
	return $main_output;
}

#remove none hyperlink marking code
function RemoveHyperlink($main_output,$start_tag,$end_tag){
	$main_output=str_replace($start_tag,'',$main_output);
	$main_output=str_replace($end_tag,'',$main_output);
	return $main_output;
}

#replace the sup and sub tags 
function ReplaceSupSub($main_output){
	$main_output=str_ireplace("<sup>","<font face='Superscript'>","$main_output");
	$main_output=str_ireplace("</sup>","</font>","$main_output");
	$main_output=str_ireplace("<sub>","<font face='Subscript'>","$main_output");
	$main_output=str_ireplace("</sub>","</font>","$main_output");
	return $main_output;
}

#replace the marked keyword
function marked_keyword_replace($main_output="",$seaching_content=array()){
	
	preg_match_all("#\*(\<|\&lt;)\*(.+?)\*(\>|\&gt;)\*#", $main_output, $matches);
	
	foreach($seaching_content as $gl_key=>$gl_value){	
	
			$Popup_value = $gl_value['gl_descripto'];
								
			#SET SEARCHING ITEM
			$search_item = $gl_value['gl_term'];
								
			$search_item_lowercase = strtolower($gl_value['gl_term']);

			$search_item_uppercase = strtoupper($search_item_lowercase);

			$search_item_ucfirst = ucfirst($search_item_lowercase);
			
			#REPLACE THE ' with \'
			$search_item1 =  str_replace("'","\'",$search_item);
			
			$search_item_lowercase1 = str_replace("'","\'",$search_item_lowercase);
			
			$search_item_uppercase1 = str_replace("'","\'",$search_item_uppercase);
			
			$search_item_ucfirst1 = str_replace("'","\'",$search_item_ucfirst);
			
			$search_item_withfonts = ReplaceFontFamily($gl_value['gl_term']);
			
			$array_lowercase = explode(" ",$search_item_lowercase);
			
			
			$i=0;
			foreach($array_lowercase as $array_lowercase_item){
				$array_lowercase[$i]=ucfirst($array_lowercase_item);
				$i++;
			}
			
			$search_item_captial_header=implode(" ",$array_lowercase);
			
			$term_link = "<a id=\"".$search_item."\" href=\"javascript:ShowGlossaryPopup('popup','".Encoding($gl_value['gl_descripto'])."');\"  style=\"text-decoration:none;color:#808080;\" onmouseover=\"omoChangeFont('".$search_item1."')\" onmouseout=\"omoChangeFontBack('".$search_item1."')\" >***".$search_item."###</a>";
			
			$term_link_lowercase = "<a id=\"".$search_item_lowercase."\" href=\"javascript:ShowGlossaryPopup('popup','".Encoding($gl_value['gl_descripto'])."');\" style=\"text-decoration:none;color:#808080;\" onmouseover=\"omoChangeFont('".$search_item_lowercase1."')\" onmouseout=\"omoChangeFontBack('".$search_item_lowercase1."')\" >***".$search_item_lowercase."###</a>";
			
			$term_link_uppercase = "<a id=\"".$search_item_uppercase."\" href=\"javascript:ShowGlossaryPopup('popup','".Encoding($gl_value['gl_descripto'])."');\" style=\"text-decoration:none;color:#808080;\" onmouseover=\"omoChangeFont('".$search_item_uppercase1."')\" onmouseout=\"omoChangeFontBack('".$search_item_uppercase1."')\">***".$search_item_uppercase."###</a>";
			
			$term_link_ucfirst = "<a id=\"".$search_item_ucfirst."\" href=\"javascript:ShowGlossaryPopup('popup','".Encoding($gl_value['gl_descripto'])."');\" style=\"text-decoration:none;color:#808080;\" onmouseover=\"omoChangeFont('".$search_item_ucfirst1."')\" onmouseout=\"omoChangeFontBack('".$search_item_ucfirst1."')\">***".$search_item_ucfirst."###</a>";
			
			$term_link_captial_header = "<a id=\"".$search_item_captial_header."\" href=\"javascript:ShowGlossaryPopup('popup','".Encoding($gl_value['gl_descripto'])."');\" style=\"text-decoration:none;color:#808080;\" onmouseover=\"omoChangeFont('".$search_item_captial_header."')\" onmouseout=\"omoChangeFontBack('".$search_item_captial_header."')\">***".$search_item_captial_header."###</a>";
			
			$term_link_withfonts = "<a id=\"".$gl_value['gl_term']."\" href=\"javascript:ShowGlossaryPopup('popup','".Encoding($gl_value['gl_descripto'])."');\" style=\"text-decoration:none;color:#808080;\" onmouseover=\"omoChangeFont('".$gl_value['gl_term']."')\" onmouseout=\"omoChangeFontBack('".$gl_value['gl_term']."')\">***".$search_item_withfonts."###</a>";

			foreach($matches[0] as $matches_key_sub_p_a=>$matches_value_sub_p_a){
				
				$searching_item_final="";
			
				$replacing_item_final="";
										
				if($matches_value_sub_p_a=="*<*".$search_item."*>*"){
						$searching_item_final="*<*".$search_item."*>*";
						$replacing_item_final=$term_link;
				}
				
				if($matches_value_sub_p_a=="*<*".$search_item_lowercase."*>*"){
						$searching_item_final="*<*".$search_item_lowercase."*>*";
						$replacing_item_final=$term_link_lowercase;
				}
				
				if($matches_value_sub_p_a=="*<*".$search_item_lowercase."s*>*"){
						$searching_item_final="*<*".$search_item_lowercase."s*>*";
						$replacing_item_final="<a href=\"javascript:ShowGlossaryPopup('popup','".Encoding($gl_value['gl_descripto'])."');\" style=\"text-decoration:none;color:#808080;\" onmouseover=\"omoChangeFont('".$gl_value['gl_term']."')\" onmouseout=\"omoChangeFontBack('".$gl_value['gl_term']."');\">".$search_item_lowercase."s</a>";
				}
				
				if($matches_value_sub_p_a=="*<*".$search_item_uppercase."*>*"){
						$searching_item_final="*<*".$search_item_uppercase."*>*";
						$replacing_item_final=$term_link_uppercase;
				}
				
				if($matches_value_sub_p_a=="*<*".$search_item_uppercase."s*>*"){
						$searching_item_final="*<*".$search_item_uppercase."s*>*";
						$replacing_item_final="<a href=\"javascript:ShowGlossaryPopup('popup','".Encoding($gl_value['gl_descripto'])."');\">".$search_item_uppercase."s</a>";
				}
				
				if($matches_value_sub_p_a=="*<*".$search_item_ucfirst."*>*"){
						$searching_item_final="*<*".$search_item_ucfirst."*>*";
						$replacing_item_final=$term_link_ucfirst;
				}
				
				if($matches_value_sub_p_a=="*<*".$search_item_ucfirst."s*>*"){
						$searching_item_final="*<*".$search_item_ucfirst."s*>*";
						$replacing_item_final="<a href=\"javascript:ShowGlossaryPopup('popup','".Encoding($gl_value['gl_descripto'])."');\">".$search_item_ucfirst."s</a>";
				}
				
				if($matches_value_sub_p_a=="*<*".$search_item_captial_header."*>*"){
						$searching_item_final="*<*".$search_item_captial_header."*>*";
						$replacing_item_final=$term_link_captial_header;
				}	
				
				if($matches_value_sub_p_a=="*<*".$search_item_withfonts."*>*"){
						$searching_item_final="*<*".$search_item_withfonts."*>*";
						$replacing_item_final=$term_link_withfonts;
				}
				
				
				if($matches_value_sub_p_a=="*&lt;*".$search_item."*&gt;*"){
						$searching_item_final="*&lt;*".$search_item."*&gt;*";
						$replacing_item_final=$term_link;
				}
				
				if($matches_value_sub_p_a=="*&lt;*".$search_item_lowercase."*&gt;*"){
						$searching_item_final="*&lt;*".$search_item_lowercase."*&gt;*";
						$replacing_item_final=$term_link_lowercase;
				}
				
				if($matches_value_sub_p_a=="*&lt;*".$search_item_uppercase."*&gt;*"){
						$searching_item_final="*&lt;*".$search_item_uppercase."*&gt;*";
						$replacing_item_final=$term_link_uppercase;
				}
				
				if($matches_value_sub_p_a=="*&lt;*".$search_item_ucfirst."*&gt;*"){
						$searching_item_final="*&lt;*".$search_item_ucfirst."*&gt;*";
						$replacing_item_final=$term_link_ucfirst;
				}
				
				if($matches_value_sub_p_a=="*&lt;*".$search_item_captial_header."*&gt;*"){
						$searching_item_final="*&lt;*".$search_item_captial_header."*&gt;*";
						$replacing_item_final=$term_link_captial_header;
				}
				//echo "searching_item_final:".$searching_item_final."</br>";
				//echo "replacing_item_final:".$replacing_item_final."</br>";
				$replacement_Item=str_replace($searching_item_final,$replacing_item_final,$matches_value_sub_p_a);				                
				$main_output=str_replace($matches_value_sub_p_a,$replacement_Item,$main_output);			
			}					
	}	
	return $main_output;
}

#replace the reference identifier
function Replace_reference($main_output){
	
	preg_match_all("#\<reference\>(.+?)\</reference\>#", $main_output, $matches);
	
	$search_item="";
	
	$replace_item="";
	
	foreach($matches[0] as $matches_key=>$matches_value){
		
		if($matches_value=="<reference>1</reference>"){
			$search_item="<reference>1</reference>";
			$replace_item="<a href=\"javascript:OpenReference(1);\">Reference</a>";
		}
		else if($matches_value=="<reference>2</reference>"){
			$search_item="<reference>2</reference>";
			$replace_item="<a href=\"javascript:OpenReference(2);\">Reference</a>";
		}
		else if($matches_value=="<reference>3</reference>"){
			$search_item="<reference>3</reference>";
			$replace_item="<a href=\"javascript:OpenReference(3);\">Reference</a>";
		}
		
		$replacement_Item=str_replace($search_item,$replace_item,$matches_value);
		
		$main_output=str_replace($matches_value,$replacement_Item,$main_output);
	}
	
	return $main_output;
}

#control the font-family of the page content
function ReplaceFontFamily($main_output){
	
	preg_match_all("#\&\#(.+?)\;#", $main_output, $matches);
	
	$search_item="";
			
	$replace_item="";
			
	foreach($matches[0] as $matches_key=>$matches_value){

		$search_item=$matches_value;
		
		$replace_item="<span style=\"font-family:Times New Roman;font-size:medium;\">".$matches_value."</span>";
		
		if(!strpos($main_output, $replace_item)){
		
			$main_output=str_replace($matches_value,$replace_item,$main_output);
		}
		
	}

	return $main_output;
}

#Fix the image tags
function imageRepair($main_output){
	
	preg_match_all("#\<(img|IMG)(.+?)\>#", $main_output, $matches);
	
	$flag_replace=false;
	
	$mode_replace="n";
	
	$replaced_hight=0;
	
	$replaced_width=0;
	
	foreach($matches[0] as $matches_key=>$matches_value){
		
		preg_match_all("#src\=\"(.+?)\"#",$matches_value,$matches_src);
		
		$newIMAGEtag="";
		
		$newIMAGEtag.="<IMG ";
		
		if(strpos($matches_value,'height')==true){
			
			if(strpos($matches_value,'width')==true){
				
				$flag_replace=false;
				$mode_replace="a";
				
			}
			else{
					
				$flag_replace=true;
				$mode_replace="h";
					
			}
		}
		else if(strpos($matches_value,'width')==true){
			
			if(strpos($matches_value,'height')==true){
				
				$flag_replace=false;
				$mode_replace="a";
				
			}	
			else{
				
				$flag_replace=true;
				$mode_replace="w";
				
			}
		}
		
		else{
			
			$flag_replace=true;
			$mode_replace="n";
			
		}
		
		
		foreach($matches_src[1] as $matches_src_key=>$matches_src_value){
			
			$newIMAGEtag.="src=\"".$matches_src_value."\" ";
			
			$size = getImageSize($matches_src_value);
			
			if($mode_replace=="n"){
				
				$replaced_width=$size[0];
				
				$replaced_hight=$size[1];	
				
			}
			else if($mode_replace=="h"){
				
				preg_match_all("#height\=\"(.+?)\"#",$matches_value,$matches_height);
				
				foreach($matches_height[1] as $matches_height_value){
					
					$replaced_hight=$matches_height_value;
					
					$replaced_width=$replaced_hight*$size[0]/$size[1];
					
				}
			}
			else if($mode_replace=="w"){
				
				preg_match_all("#width\=\"(.+?)\"#",$matches_value,$matches_width);
				
				foreach($matches_width[1] as $matches_width_value){
					
					$replaced_width=$matches_width_value;
					
					$replaced_hight=$replaced_width*$size[1]/$size[0];
	
				}
			}
			
			$newIMAGEtag.="height=\"".$replaced_hight."px\" ";
			
			$newIMAGEtag.="width=\"".$replaced_width."px\"";
			
			$newIMAGEtag.="/>";
		}
		
		if($flag_replace==true){
		
			$main_output=str_replace($matches_value,$newIMAGEtag,$main_output);
		
		}
		
	}
	
	return $main_output;
	
}

#remove the flash code when generate PDF
function remove_flash($main_output){
	
	$main_output = preg_replace('#\<object(.+?)\<\/object\>#','',$main_output);
	
	return $main_output;
}

#encoding the glossary descritpion
function Encoding($content){
	
	$content = str_ireplace("%0a","",urlencode($content));
	$content = str_ireplace("%0d","<enter/>",$content);
	
	return $content;
}

#Change the style of hyper link in font side of this system 
function ChangeHyperLinkStyle($main_output){
	
	preg_match_all("#\<a(.+?)\>#", $main_output, $matches);
	
	foreach($matches[1] as $matches_data){
		
		if($matches_data != " href=\"www.uq.edu.au\""){
			$search_item = $matches_data;
			$replaced_item = $matches_data." class=\"external\" TARGET = \"_blank\"";
			$main_output=str_replace($matches_data,$replaced_item,$main_output);
		}
	}
	
	return $main_output;
}

#Replace the hyperlink url for PDF
function replace_hyperlink_url($main_output){
	
	preg_match_all("#\<a(.+?)\>#", $main_output, $matches);
	
	foreach($matches[0] as $matches_data){
		
		$search_item = "../";
			
		$replaced_item = "../";
			
		$replaced_result = str_replace($search_item,$replaced_item,$matches_data);
		
		if(!strpos($main_output, $replace_item)){
			$main_output=str_replace($matches_data,$replaced_result,$main_output);
		}
	}
	
	return $main_output;
}

#Put wmode="transparent" into embedded tag
function InsertWmode($main_output){
	
	preg_match_all("#\<embed(.+?)\/\>#", $main_output, $matches);
	
	foreach($matches[1] as $matches_data){
		
		$replaced_result = $matches_data."wmode=\"transparent\"";
		
		$main_output=str_replace($matches_data,$replaced_result,$main_output);
	}
	
	return $main_output;
}

#remove tables and paragraph tags
function Remove_TP_Tag($page_content){
	
	#remove table header
	$page_content = preg_replace("#\<table(.+?)\>#", "", $page_content);
	
	#remove table end
	$page_content = str_replace("</table>", "", $page_content);
	
	#remove tr header
	$page_content = preg_replace("#\<tr(.+?)\>#", "", $page_content);
	
	#remove td header	
	$page_content = preg_replace("#\<td(.+?)\>#", "", $page_content);
	
	#remove tr end
	$page_content = str_replace("</tr>", "", $page_content);
	
	#remove td end
	$page_content = str_replace("</td>", "", $page_content);
	
	preg_match_all("#\<p class\=\"LEFT\"\>(.+?)\<\/p\>#", $page_content, $matches);
	
	foreach($matches[0] as $matches_data){
		
		#remove paragraph header
		$replaced_data = str_replace("<p class=\"LEFT\">","",$matches_data);
	
		#remove paragraph end
		$replaced_data = str_replace("</p>","",$replaced_data);
		
		$page_content = str_replace($matches_data,$replaced_data,$page_content);
	}
	
	return $page_content;
}


?>